import { DragSortTable, EditableProTable, ModalForm } from "@ant-design/pro-components"
import { Button, Form, FormInstance, Popconfirm, message } from "antd";
import { useState, } from "react";
import { PlusOutlined } from "@ant-design/icons";
import ApiForm from "@/pages/api-auto/api/form";
import CustomCode from "@/components/CustomCode";

const CustomDragTable = ({
    form,
    value,
    onChange,
    data,
}: {
    form?: FormInstance<any>
    [key: string]: any,
}) => {
    const [apiForm] = Form.useForm()
    const [showModal, setShowModal] = useState(false)
    const [currentEdit, setCurrentEdit] = useState('header')
    const [isEdit, setEdit] = useState(false)

    return <>
        <ModalForm
            title={isEdit ? '编辑步骤' : '新增步骤'}
            open={showModal}
            trigger={<Button
                onClick={() => {
                    setEdit(false)
                }}
                icon={<PlusOutlined />}
                style={{ marginBottom: 15 }}
            >新增</Button>}
            modalProps={{
                width: 1000,
                destroyOnClose: true,
                onCancel() {
                    setShowModal(false)
                    setCurrentEdit('header')
                },
            }}
            form={apiForm}
            autoFocusFirstInput
            submitTimeout={2000}
            onFinish={async (values) => {
                const steps = value || []
                if (isEdit) {
                    const newSteps = steps.map((item: any) => {
                        if (item.key == values.key) {
                            item = {
                                ...item,
                                ...values
                            }
                        }
                        return item
                    })
                    onChange?.([...newSteps])
                } else {
                    steps.push({
                        ...values,
                        key: Date.now(),
                    })
                    onChange?.([...steps])
                }
                setShowModal(false)
                setCurrentEdit('header')
                return true
            }}
        >
            <ApiForm
                form={apiForm}
                tabList={[
                    { label: '请求头', key: 'header' },
                    { label: '请求体', key: 'body' },
                    { label: '查询参数', key: 'query' },
                    { label: '关联变量', key: 'relation' },
                    { label: '断言', key: 'assertion' },
                ]}
                onTabChange={(val: any) => {
                    setCurrentEdit(val)
                }}>
                <div style={{ display: currentEdit == 'relation' ? 'block' : 'none' }}>
                    <EditableProTable<any>
                        rowKey="key"
                        maxLength={5}
                        name={'relation'}
                        recordCreatorProps={{
                            position: 'bottom',
                            record: () => ({ key: (Math.random() * 1000000).toFixed(0) }),
                        }}
                        toolBarRender={false}
                        loading={false}
                        columns={[
                            {
                                title: '关联来源',
                                dataIndex: 'from',
                                valueType: 'select',
                                valueEnum: {
                                    REQUEST_HEADER: { text: '请求头' },
                                    REQUEST_BODY: { text: '请求体' },
                                    REQUEST_QUERY: { text: '请求查询参数' },
                                    RESPONSE_HEADER: { text: '响应头' },
                                    RESPONSE_DATA: { text: '响应体' },
                                }
                            },
                            {
                                title: '关联类型',
                                dataIndex: 'type',
                                valueType: 'select',
                                valueEnum: {
                                    REGEXP: { text: '正则' },
                                    JSONPATH: { text: 'JSONPATH规则' },
                                }
                            },
                            {
                                title: '关联表达式',
                                dataIndex: 'express',
                            },
                            {
                                title: '关联变量名',
                                dataIndex: 'name',
                            },
                            {
                                title: '操作',
                                valueType: 'option',
                                render: (text, record, _, action) => [
                                    <a
                                        key="editable"
                                        onClick={() => {
                                            action?.startEditable?.(record.key);
                                        }}
                                    >
                                        编辑
                                    </a>,
                                    <a
                                        key="delete"
                                        onClick={() => {
                                            const tableDataSource = apiForm?.getFieldValue('relation',) as any[];
                                            apiForm?.setFieldsValue({
                                                relation: tableDataSource?.filter((item) => item.key !== record.key),
                                            });
                                        }}
                                    >
                                        删除
                                    </a>,
                                ],
                            },

                        ]}
                        editable={{
                            type: 'multiple',
                        }}
                    />
                </div>
                <div style={{ display: currentEdit == 'assertion' ? 'block' : 'none' }}>
                    <EditableProTable<any>
                        rowKey="key"
                        maxLength={5}
                        name={'assertion'}
                        recordCreatorProps={{
                            position: 'bottom',
                            record: () => ({ key: (Math.random() * 1000000).toFixed(0) }),
                        }}
                        toolBarRender={false}
                        loading={false}
                        columns={[
                            {
                                title: '断言来源',
                                dataIndex: 'from',
                                valueType: 'select',
                                valueEnum: {
                                    RESPONSE_CODE: { text: '响应码' },
                                    RESPONSE_HEADER: { text: '响应头' },
                                    RESPONSE_DATA: { text: '响应体' },
                                }
                            },
                            {
                                title: '断言类型',
                                dataIndex: 'type',
                                valueType: 'select',
                                valueEnum: {
                                    REGEXP: { text: '正则' },
                                    JSONPATH: { text: 'JSONPATH规则' },
                                }
                            },
                            {
                                title: '断言动作',
                                dataIndex: 'action',
                                valueType: 'select',
                                valueEnum: {
                                    CONTAIN: { text: '包含' },
                                    NOT_CONTAIN: { text: '不包含' },
                                    EQUAL: { text: '等于' },
                                    NOT_EQUAL: { text: '不等于' },
                                    GREAT_THEN: { text: '大于' },
                                    LESS_THEN: { text: '小于' },
                                    GREAT_THEN_OR_EQUAL: { text: '大于等于' },
                                    LESS_THEN_OR_EQUAL: { text: '小于等于' },
                                }
                            },
                            {
                                title: '关联表达式',
                                dataIndex: 'express',
                            },
                            {
                                title: '预期值',
                                dataIndex: 'value',
                            },
                            {
                                title: '操作',
                                valueType: 'option',
                                render: (text, record, _, action) => [
                                    <a
                                        key="editable"
                                        onClick={() => {
                                            action?.startEditable?.(record.key);
                                        }}
                                    >
                                        编辑
                                    </a>,
                                    <a
                                        key="delete"
                                        onClick={() => {
                                            console.log(form, apiForm?.getFieldsValue());

                                            const tableDataSource = apiForm?.getFieldValue(
                                                'assertion',
                                            ) as any[];
                                            console.log('tableDataSource', tableDataSource);

                                            apiForm?.setFieldsValue({
                                                assertion: tableDataSource?.filter((item) => item.key !== record.key),
                                            });
                                        }}
                                    >
                                        删除
                                    </a>,
                                ],
                            },

                        ]}
                        editable={{
                            type: 'multiple',
                        }}
                    />
                </div>
                <Form.Item name={'key'} noStyle></Form.Item>
            </ApiForm>
        </ModalForm>
        <DragSortTable<any>
            scroll={{ x: 'max-content' }}
            columns={[
                {
                    title: '',
                    dataIndex: 'num',
                    fixed: 'left',
                    width: 40,
                },
                {
                    title: '序号',
                    valueType: 'indexBorder',
                    fixed: 'left',
                    width: 60
                },
                {
                    title: '步骤名称',
                    dataIndex: 'name',
                    fixed: 'left',
                    ellipsis: true,
                    // width: 150,
                },
                {
                    title: '请求路径',
                    dataIndex: 'path'
                },
                {
                    title: '请求方法',
                    dataIndex: 'method'
                },
                {
                    title: '请求体格式',
                    dataIndex: 'bodyType',
                },
                {
                    title: '请求体',
                    dataIndex: 'body',
                    render(dom, entity, index, action, schema) {
                        let body = ''
                        if (entity?.bodyType != 'NONE') {
                            body = JSON.stringify(entity?.[entity?.bodyType])
                        }
                        return <CustomCode width={340} height={120} value={body} />
                    },
                },
                {
                    title: '查询参数',
                    dataIndex: 'query',
                    render(dom, entity, index, action, schema) {
                        return <CustomCode width={340} height={120} value={entity?.query} />
                    },
                },
                {
                    title: '请求头',
                    dataIndex: 'header',
                    render(dom, entity, index, action, schema) {
                        return <CustomCode width={340} height={120} value={entity?.header} />
                    },
                },
                {
                    title: '响应断言',
                    dataIndex: 'assertion',
                    render(dom, entity, index, action, schema) {
                        return <CustomCode width={340} height={120} value={entity?.assertion} />
                    },
                },
                {
                    title: '关联参数',
                    dataIndex: 'relation',
                    render(dom, entity, index, action, schema) {
                        return <CustomCode width={340} height={120} value={entity?.relation} />
                    },
                },
                {
                    title: '步骤描述',
                    dataIndex: 'description',
                    ellipsis: true,
                    render(dom, entity, index, action, schema) {
                        return <div style={{ width: 200 }}>{dom}</div>
                    },
                },
                {
                    title: '创建时间',
                    dataIndex: 'gmtCreate',
                    valueType: 'dateTime',
                },
                {
                    title: '更新时间',
                    dataIndex: 'gmtModified',
                    valueType: 'dateTime',
                },
                {
                    title: '操作',
                    dataIndex: 'option',
                    valueType: 'option',
                    fixed: 'right',
                    render: (_, record: any, index) => [
                        <a key={'edit'} onClick={() => {
                            setShowModal(true)
                            setEdit(true)
                            apiForm.setFieldsValue({
                                ...record
                            })
                        }}>编辑</a>,
                        <Popconfirm key='del' title="是否要删除此行？" onConfirm={() => {
                            const steps = value || []
                            const newSteps = steps?.filter((item: any) => item.key !== record?.key)
                            onChange?.(newSteps)
                        }}>
                            <a onClick={() => {
                            }}>删除</a>
                        </Popconfirm>

                    ],
                },
            ]}
            dataSource={value}
            rowKey={'key'}
            toolBarRender={false}
            search={false}
            pagination={false}
            dragSortKey="num"
            onDragSortEnd={(
                beforeIndex: number,
                afterIndex: number,
                newDataSource: any,
            ) => {
                onChange?.(newDataSource);
                // message.success('修改列表排序成功');
            }}
        />
    </>
}

export default CustomDragTable